package com.framework.bdf4j.comm.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.framework.bdf4j.comm.Constants;
import com.framework.bdf4j.comm.util.R;

import lombok.extern.slf4j.Slf4j;

/**
 * <b>文件名： </b>ExceptionProcessor.java<br/>
 * <b>类描述： </b>Controller统一异常处理器<br/>
 */
@Slf4j
@ControllerAdvice
public class ExceptionProcessor {

    @ExceptionHandler(Exception.class)
    public String exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) {

        log.error("全局异常信息 ex={}", ex.getMessage(), ex);

        HttpSession session = request.getSession();
        // 判断是否ajax请求，如果不是则跳转到错误页面
        if (!(request.getHeader("accept").indexOf("application/json") > -1
            || (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {
            session.setAttribute(Constants.ERROR_MSG,
                StringUtils.isBlank(ex.getMessage()) ? ExceptionUtil.getExceptionMessage(ex) : ex.getMessage());
            return "redirect:/page/error";
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");

            try {
                response.getWriter().write(toJson(R.failed(
                    StringUtils.isBlank(ex.getMessage()) ? ExceptionUtil.getExceptionMessage(ex) : ex.getMessage())));
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }

    protected String toJson(Object object) {
        return JSON.toJSONString(object, SerializerFeature.BrowserCompatible);
    }
}
